import os, sys
import csv

folder_path = raw_input("Enter path for folder that contains csv files:")

print "The path is: " + folder_path

if not os.path.isdir(folder_path):
	print "The path is incorrect."
	sys.exit()
else:
	print "The path has been found."

with open(os.path.join(folder_path, "result.csv"), "wb" ) as f_out:
	csv_writer = csv.writer(f_out)
	print "Output file has been opened."

	csv_file_names = []
	for root,dirs,files in os.walk(folder_path):
	    for file in files:
	        if file.endswith(".csv") and not file.startswith("result"):
	        	csv_file_names.append(file)

	print "The following csv files have been found: ", csv_file_names

	# get the data from the files
	raw_data = {}
	for csv_file_name in csv_file_names:
		with open(os.path.join(folder_path, csv_file_name), "r") as csv_file:
			data_reader = csv.reader(csv_file)
			rows = []
			raw_data[csv_file_name] = {"headers":data_reader.next(), "data": rows}
			for row in data_reader:
				rows.append(row) 

	# get the step size
	step_size = raw_input("Enter the time increment for the time series:")
	try:
		step_size = int(step_size)
	except:
		print "The step size is invalid."
		sys.exit()


	# create the new header
	new_header = ["at_time"] 
	for k in raw_data.keys():
		for c in raw_data[k]["headers"][3:]:
			new_header.append(k[:-4]+"_"+c+"_min")
			new_header.append(k[:-4]+"_"+c+"_max")
			new_header.append(k[:-4]+"_"+c+"_avg")
	print new_header
	csv_writer.writerow(new_header)

	# get max death time
	death_times = []
	for k in raw_data.keys():
		data = raw_data[k]["data"] 
		death_column = [int(r[2]) for r in data if r[2] != "None"]
		death_times.extend(death_column)
	max_death = max(death_times)

	# get the data for each row from all the files
	for counter in range(1, max_death, step_size):
		new_row = [counter]
		for k in raw_data.keys():
			headers = raw_data[k]["headers"]
			data = raw_data[k]["data"] 
			print k, "counter = ", counter
			for c in range(3, len(headers)):
				print "    column = ", headers[c]
				# conditions for this counter
				column = [[r[0], float(r[c])] for r in data if 
					r[c] != "None" and 
					int(r[1]) <= counter  and  
					(r[2] == "None" or int(r[2]) > counter)]
				print column
				if column:
					new_row.append(min([r[1] for r in column]))
					new_row.append(max([r[1] for r in column]))
					new_row.append(sum([r[1] for r in column]) / float(len(column)))
				else:
					new_row.append(None)
					new_row.append(None)
					new_row.append(None)
		csv_writer.writerow(new_row)

print "done!"